//
//  RecommendViewController.m
//  PlayerFix
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 DAT. All rights reserved.
//

#import "RecommendViewController.h"
#import "RecommendCell.h"
#import "DATAsyncGetAFNBlock.h"
#import "DATAsyncPostAFNBlock.h"
#import "RecommendModel.h"
#import "ZQW_ScrollView.h"
#import "RecommendDetailViewController.h"
#import <MJRefresh.h>



@interface RecommendViewController ()<UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionVC;
@property (nonatomic, strong) NSMutableArray *dataCountArray;

@property (nonatomic, strong) ZQW_ScrollView *carouselView;
@property (nonatomic, strong) NSArray *carouselArray;

@property(nonatomic,assign)NSInteger page;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉



@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    if (self.navigationController) {
        NSLog(@"bbbbbbbbbbbbbb");
    }
    
    //创建UICollectionViewLayout的子类   因为这是一个抽象类,代表瀑布流的风格和样式
    //使用UICollectionViewLayout的子类UICollectionViewFlowLayout来布局瀑布流的样式
    //UICollectionView只是负责滚动和显示
    
    //是苹果提供的标准的瀑布流的样式
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //设置item大小
    flowLayout.itemSize = CGSizeMake(170, 215);
    //设置item的列间距
    flowLayout.minimumInteritemSpacing = 15;
    //设置item的行间距
    flowLayout.minimumLineSpacing = 15;
    //设置item上,左,下,右边界距离
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    //头部区域大小
    flowLayout.headerReferenceSize = CGSizeMake(375, 220);
    //滑动方向(水平 竖直)
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    
    //创建UICollectionView
    self.collectionVC = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 375, 667 - 30 - 64) collectionViewLayout: flowLayout ];
    self.collectionVC.backgroundColor = [UIColor whiteColor];
    
    self.collectionVC.delegate = self;
    self.collectionVC.dataSource = self;
    
    
    self.carouselView = [[ZQW_ScrollView alloc] initWithFrame:CGRectMake(10, 5, 355, 180)];
    
    
    //注册cell  不注册会崩溃
    [self.collectionVC registerClass:[RecommendCell class] forCellWithReuseIdentifier:@"reuse"];
    //注册表头和底部视图
    [self.collectionVC registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [self.view addSubview:self.collectionVC];

    self.dataCountArray = [NSMutableArray array];
    self.carouselArray = [NSArray array];

    [self getAFNetworkingData];
    //[self getCarcouselData];
    
    
    /* ******************* 轮播图 ******************* */
    self.carouselView = [[ZQW_ScrollView alloc] initWithFrame:CGRectMake(10, 5, 355, 180)];
    self.carouselView.currentColor = [UIColor whiteColor];
    self.carouselView.allColor = [UIColor lightGrayColor];
    self.carouselView.autoScrollTimeInterval = 2;
    //self.carouselView.Delegate = self;
    [self getCarouselData];
    [self.collectionVC addSubview:self.carouselView];
    
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    headerLabel.backgroundColor = [UIColor colorWithRed:206 / 255.0 green:255 / 255.0 blue:205 / 255.0 alpha:1.0];
    headerLabel.textColor = [UIColor colorWithRed:101 / 255.0 green:149 / 255.0 blue:97 / 255.0 alpha:1.0];
    headerLabel.layer.masksToBounds = YES;
    headerLabel.layer.cornerRadius = 15;
    headerLabel.font = [UIFont systemFontOfSize:15];
    headerLabel.textAlignment = NSTextAlignmentCenter;
    headerLabel.text = @"MixPlayer 今日推荐";
    headerLabel.center = CGPointMake(self.view.frame.size.width / 2, 210);
    [self.collectionVC addSubview:headerLabel];
    
    
    self.isUpLoading = NO;
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
}

#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block RecommendViewController *recommendVC = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    
    self.collectionVC.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态就会回调这个Block
        
        recommendVC.page = 1;//记录页码的
        recommendVC.isUpLoading = NO;//标记为下拉操作
        [recommendVC getAfnDataWithPage:recommendVC.page];//重新请求数据
        
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.collectionVC.header endRefreshing];
    });
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.collectionVC.header beginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    
    //    __unsafe_unretained typeof(self) vc = self;
    __unsafe_unretained RecommendViewController *recommendVC = self;
    
    
    self.collectionVC.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        // 进入刷新状态就会回调这个Block
        
        recommendVC.page += 1;
        recommendVC.isUpLoading = YES;//标记为上拉操作
        [recommendVC getAfnDataWithPage:recommendVC.page];//请求数据

    }];
    
    // 添加上拉刷新尾部控件
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.collectionVC.footer endRefreshing];
    });

    
    
}

- (void)getAfnDataWithPage:(NSInteger)page{
    
    [DATAsyncGetAFNBlock GetAFNURLWithString:[NSString stringWithFormat:@"http://echosystem.kibey.com/sound/hot?page=%ld",page] andBody:nil andCookie:nil resultBlock:^(id result) {
        //NSLog(@"result ============= %@", result);
        NSDictionary *resultDic = [result objectForKey:@"result"];
        //NSLog(@"resultDic = %@", resultDic);
        NSArray *dataArray = [resultDic objectForKey:@"data"];
        for (NSDictionary *dic in dataArray) {
            
//            NSLog(@"dic = %@", dic);
            RecommendModel *recommend = [[RecommendModel alloc] init];
            recommend.channel = [dic objectForKey:@"channel"];
            [recommend setValuesForKeysWithDictionary:dic];
            [self.dataCountArray addObject:recommend];
            
        
            //[self.collectionVC headerEndRefreshing];

            [self.collectionVC.header endRefreshing];
            [self.collectionVC.footer endRefreshing];
        }
        
        [self.collectionVC reloadData];
        
    } errorBlock:^(NSError *error) {
        
//        NSLog(@"RecommendAFNError ============ %@", error);
        
//        [self.bgTableView footerEndRefreshing];
//        [self.bgTableView headerEndRefreshing];
        
        [self.collectionVC.header endRefreshing];
        [self.collectionVC.footer endRefreshing];


    }];

}




- (void)getAFNetworkingData{
    
    [DATAsyncGetAFNBlock GetAFNURLWithString:@"http://echosystem.kibey.com/sound/hot?page=1" andBody:nil andCookie:nil resultBlock:^(id result) {
        //NSLog(@"result ============= %@", result);
        NSDictionary *resultDic = [result objectForKey:@"result"];
        //NSLog(@"resultDic = %@", resultDic);
        NSArray *dataArray = [resultDic objectForKey:@"data"];
        for (NSDictionary *dic in dataArray) {
            
//            NSLog(@"dic = %@", dic);
            RecommendModel *recommend = [[RecommendModel alloc] init];
            recommend.channel = [dic objectForKey:@"channel"];
            [recommend setValuesForKeysWithDictionary:dic];
            [self.dataCountArray addObject:recommend];
         
            [self.collectionVC.header endRefreshing];
            [self.collectionVC.footer endRefreshing];

        }
        
        [self.collectionVC reloadData];
        
    } errorBlock:^(NSError *error) {
        
        NSLog(@"RecommendAFNError ============ %@", error);
        [self.collectionVC.header endRefreshing];
        [self.collectionVC.footer endRefreshing];

    }];
    
    
}

- (void)getCarouselData{
    
    [DATAsyncPostAFNBlock PostAFNURLWithString:@"http://api2.pianke.me/ting/radio" Body:@{@"auth":@"", @"client":@"1",@"deviceid":@"5F17F991-0D41-4B6E-AAC0-4DC946A29CAD",@"version":@"3.0.6"} Cookie:@"PHPSESSID=58ts41v1nohdn89damknm0vdt5" resultBlock:^(id result) {
        
//        NSLog(@" =============== %@", result);
        NSMutableDictionary *dic = [result objectForKey:@"data"];
        NSMutableArray *carouselArr = [dic objectForKey:@"carousel"];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dic in carouselArr) {
            
//            NSLog(@"carouselDic ============ %@",dic);
            NSString *imgurl = [dic objectForKey:@"img"];
            [tempArray addObject:imgurl];
//            NSLog(@"carouselImages =========== %@",tempArray);
        }
        self.carouselArray = tempArray;
        self.carouselView.pictureArray = (NSMutableArray *)self.carouselArray;
//        NSLog(@"carouselImages ================ %@",self.carouselArray);
        
    } errorBlock:^(NSError *error) {
        
//        NSLog(@"carouselAFNError ======= %@", error);
    }];

}

//自定义cell
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    RecommendModel *recommendModel = [self.dataCountArray objectAtIndex:indexPath.row];
    
    //直接从cell重用池里取
    RecommendCell *recommendCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    recommendCell.backgroundColor = [UIColor whiteColor];
    recommendCell.recommendModel = recommendModel;
    return recommendCell;
    
}

//设置每个item的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(170, 215);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    
    return self.dataCountArray.count;
}

//item点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    RecommendDetailViewController *recommendDetailVC = [[RecommendDetailViewController alloc] init];
    recommendDetailVC.recommend = self.dataCountArray[indexPath.row];
    recommendDetailVC.allListArray = self.dataCountArray;
    NSLog(@" push ****************** allMusicArray = %@", recommendDetailVC.recommend);
    [[SingletonForPush shareSingleton].naVC pushViewController:recommendDetailVC animated:YES];
    
    RecommendModel *recommend = [self.dataCountArray objectAtIndex:indexPath.row];
    
    NSLog(@"*************************** %@", recommend.source);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
